<template>
	<div class="app-container">
		<el-row :gutter="20">
			<!-- 左侧分类树 -->
			<el-col :span="6">
				<el-card shadow="never" class="tree-card">
					<el-button type="primary" plain @click="handleAddCategory">
						<el-icon> <plus /> </el-icon>新增分类
					</el-button>

					<div class="search-box mt-1">
						<el-input
							v-model="treeFilterText"
							placeholder="请输入分类名称"
							clearable
							prefix-icon="Search"
						/>
					</div>
					<el-tree
						ref="treeRef"
						:data="categoryTreeData"
						:props="treeProps"
						node-key="id"
						highlight-current
						:filter-node-method="filterNode"
						@node-click="handleNodeClick"
					>
						<template #default="{ node, data }">
							<span class="tree-node">
								<span>{{ node.label }}</span>
								<div>
									<el-icon @click.stop="handleEditCategory(node.data)">
										<Edit />
									</el-icon>
									<el-icon
										class=""
										style="margin-left: 10px; color: red"
										@click.stop="handleDeleteCategory(node.data.id)"
									>
										<Delete />
									</el-icon>
								</div>
							</span>
						</template>
					</el-tree>
				</el-card>
			</el-col>

			<!-- 右侧内容区 -->
			<el-col :span="18">
				<el-card shadow="never" class="content-card">
					<!-- 图表统计区域 -->
					<el-row :gutter="20" class="chart-row">
						<el-col :span="12">
							<div class="chart-container">
								<div ref="categoryChartRef" class="chart" />
							</div>
						</el-col>
						<el-col :span="12">
							<div class="chart-container">
								<div ref="statusChartRef" class="chart" />
							</div>
						</el-col>
					</el-row>

					<!-- 搜索栏 -->
					<!-- <div class="search-bar">
						<el-input
							v-model="searchForm.nameOrCode"
							placeholder="请输入物料名称/编码"
							clearable
							style="width: 300px"
							@clear="handleSearch"
							@keyup.enter="handleSearch"
						>
							<template #prefix>
								<el-icon>
									<search />
								</el-icon>
							</template>
						</el-input>
						<el-button type="primary" @click="handleAdvancedSearch">
							<el-icon> <filter /> </el-icon>高级筛选
						</el-button>
					</div> -->

					<!-- 操作按钮 -->
					<div class="operation-buttons">
						<el-button type="primary" @click="handleAddMaterial">
							<el-icon> <plus /> </el-icon>新增物料
						</el-button>
						<!-- <el-button @click="handleImport">
							<el-icon> <upload /> </el-icon>批量导入
						</el-button>
						<el-button @click="handleExport">
							<el-icon> <download /> </el-icon>导出
						</el-button> -->
						<div class="selection-info">
							已选择 {{ selectedRows.length }} 项，共
							{{ pagination.total }} 条数据
						</div>
					</div>

					<!-- 表格 -->
					<el-table
						:data="tableData"
						border
						style="width: 100%"
						v-loading="loading"
						@selection-change="handleSelectionChange"
					>
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column
							prop="materialCode"
							label="物料编码"
							align="center"
						/>
						<el-table-column
							prop="materialName"
							label="物料名称"
							align="center"
						/>
						<el-table-column
							prop="specification"
							label="规格型号"
							align="center"
						/>
						<el-table-column prop="unit" label="单位" align="center" />
						<el-table-column
							prop="manufacturer"
							label="制造商"
							align="center"
						/>
						<el-table-column
							prop="applicationScene"
							label="应用场景"
							align="center"
						>
							<template #default="{ row }">
								{{
									getDictLabel(applicationSceneOptions, row.applicationScene)
								}}
							</template>
						</el-table-column>
						<el-table-column prop="status" label="状态" align="center">
							<template #default="{ row }">
								<el-tag :type="row.status === 0 ? 'success' : 'danger'">
									{{ row.status === 0 ? "启用" : "停用" }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column
							label="操作"
							width="120"
							fixed="right"
							align="center"
						>
							<template #default="{ row }">
								<el-button link type="primary" @click="handleEdit(row)"
									>编辑</el-button
								>
								<el-button link type="danger" @click="handleDelete(row.id)"
									>删除</el-button
								>
							</template>
						</el-table-column>
					</el-table>

					<!-- 分页 -->
					<el-pagination
						class="pagination"
						v-model:current-page="pagination.currentPage"
						v-model:page-size="pagination.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pagination.total"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</el-card>
			</el-col>
		</el-row>

		<!-- 新增/编辑物料对话框 -->
		<el-dialog
			v-model="materialDialogVisible"
			:title="materialDialogTitle"
			width="50%"
			:close-on-click-modal="false"
		>
			<el-form
				:model="materialForm"
				label-width="100px"
				:rules="materialRules"
				ref="materialFormRef"
			>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="物料编码" prop="materialCode">
							<el-input
								v-model="materialForm.materialCode"
								placeholder="请输入物料编码"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="物料名称" prop="materialName">
							<el-input
								v-model="materialForm.materialName"
								placeholder="请输入物料名称"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="规格型号" prop="specification">
							<el-input
								v-model="materialForm.specification"
								placeholder="请输入规格型号"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位" prop="unit">
							<el-input v-model="materialForm.unit" placeholder="请输入单位" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="制造商" prop="manufacturer">
							<el-input
								v-model="materialForm.manufacturer"
								placeholder="请输入制造商"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="应用场景" prop="applicationScene">
							<el-select
								v-model="materialForm.applicationScene"
								placeholder="请选择应用场景"
								style="width: 100%"
							>
								<el-option
									v-for="item in applicationSceneOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="状态" prop="status">
							<el-select
								v-model="materialForm.status"
								placeholder="请选择状态"
								style="width: 100%"
							>
								<el-option label="启用" :value="0" />
								<el-option label="停用" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="分类" prop="categoryType">
							<el-cascader
								v-model="materialForm.categoryType"
								:options="categoryTreeData"
								:props="{ value: 'id', label: 'name', children: 'children' }"
								placeholder="请选择分类"
								clearable
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="技术参数" prop="technicalParams">
					<el-input
						v-model="materialForm.technicalParams"
						type="textarea"
						:rows="3"
						placeholder="请输入技术参数"
					/>
				</el-form-item>

				<el-form-item label="使用说明" prop="usageInstruction">
					<el-input
						v-model="materialForm.usageInstruction"
						type="textarea"
						:rows="3"
						placeholder="请输入使用说明"
					/>
				</el-form-item>

				<el-form-item label="维护手册" prop="maintenanceManual">
					<el-input
						v-model="materialForm.maintenanceManual"
						type="textarea"
						:rows="3"
						placeholder="请输入维护手册"
					/>
				</el-form-item>
				<el-form-item label="关联知识" prop="picture">
					<UploadFile v-model:file-ids="materialForm.files" type="file" />
				</el-form-item>
				<el-form-item label="图片" prop="picture">
					<UploadFile
						v-model:image-url="materialForm.imageUrl"
						:limit="1"
						type="image"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="materialDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitMaterialForm">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 新增分类对话框 -->
		<el-dialog
			v-model="categoryDialogVisible"
			:title="categoryDialogTitle"
			width="30%"
		>
			<el-form
				:model="categoryForm"
				label-width="100px"
				:rules="categoryRules"
				ref="categoryFormRef"
			>
				<el-form-item label="分类名称" prop="name">
					<el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
				</el-form-item>
				<el-form-item label="父级分类" prop="parentId">
					<el-cascader
						v-model="categoryForm.parentId"
						:options="categoryTreeData"
						:props="{
							value: 'id',
							label: 'name',
							children: 'children',
							checkStrictly: true,
						}"
						placeholder="请选择父级分类"
						clearable
						style="width: 100%"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="categoryDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitCategoryForm">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 高级筛选对话框 -->
		<el-dialog
			v-model="advancedSearchDialogVisible"
			title="高级筛选"
			width="50%"
		>
			<el-form :model="advancedSearchForm">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="物料编码">
							<el-input
								v-model="advancedSearchForm.materialCode"
								placeholder="请输入物料编码"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="物料名称">
							<el-input
								v-model="advancedSearchForm.materialName"
								placeholder="请输入物料名称"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="规格型号">
							<el-input
								v-model="advancedSearchForm.specification"
								placeholder="请输入规格型号"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="制造商">
							<el-input
								v-model="advancedSearchForm.manufacturer"
								placeholder="请输入制造商"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="状态">
							<el-select
								v-model="advancedSearchForm.status"
								placeholder="请选择状态"
								style="width: 100%"
							>
								<el-option label="启用" :value="0" />
								<el-option label="停用" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="分类">
							<el-cascader
								v-model="advancedSearchForm.categoryType"
								:options="categoryTreeData"
								:props="{ value: 'id', label: 'name', children: 'children' }"
								placeholder="请选择分类"
								clearable
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="advancedSearchDialogVisible = false"
						>取消</el-button
					>
					<el-button type="primary" @click="handleAdvancedSearchSubmit"
						>确定</el-button
					>
					<el-button @click="resetAdvancedSearch">重置</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, watch, nextTick } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import * as echarts from "echarts";
	import UploadFile from "@/components/UploadFile";
	import {
		Search,
		Plus,
		Upload,
		Download,
		Filter,
		Edit,
		Delete,
	} from "@element-plus/icons-vue";
	import {
		getMaterialCategoryList,
		addMaterialCategory,
		updateMaterialCategory,
		deleteMaterialCategory,
		getApplicationSceneList,
		getMaterialCatalogList,
		getMaterialCatalogDetail,
		addMaterialCatalog,
		updateMaterialCatalog,
		deleteMaterialCatalog,
		exportMaterialCatalog,
		getRatioByStatus,
		getCountByCategoryType,
	} from "@/api/prod_operate/device/asset_catalog/material_catalog";

	// 图表容器引用
	const categoryChartRef = ref(null);
	const statusChartRef = ref(null);

	// 图表实例
	let categoryChart = null;
	let statusChart = null;

	// 树形分类数据
	const categoryTreeData = ref([]);
	const treeFilterText = ref("");
	const treeRef = ref(null);

	// 树形配置
	const treeProps = {
		label: "name",
		children: "children",
	};

	// 表格数据
	const tableData = ref([]);
	const loading = ref(false);
	const selectedRows = ref([]);

	// 搜索表单
	const searchForm = reactive({
		nameOrCode: "",
		status: undefined,
		categoryType: undefined,
	});

	// 高级搜索表单
	const advancedSearchForm = reactive({
		materialCode: "",
		materialName: "",
		specification: "",
		manufacturer: "",
		status: undefined,
		categoryType: [],
	});

	// 分页数据
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0,
	});

	// 应用场景选项
	const applicationSceneOptions = ref([]);

	// 对话框相关
	const materialDialogVisible = ref(false);
	const materialDialogTitle = ref("新增物料");
	const categoryDialogVisible = ref(false);
	const categoryDialogTitle = ref("新增分类");
	const advancedSearchDialogVisible = ref(false);
	const materialFormRef = ref(null);
	const categoryFormRef = ref(null);

	// 物料表单
	const materialForm = reactive({
		id: null,
		materialCode: "",
		materialName: "",
		specification: "",
		unit: "",
		manufacturer: "",
		applicationScene: "",
		technicalParams: "",
		usageInstruction: "",
		maintenanceManual: "",
		quantity: 0,
		categoryType: [],
		status: 0,
		files: [],
		imageUrl: "",
	});

	// 分类表单
	const categoryForm = reactive({
		id: null,
		name: "",
		parentId: null,
	});

	// 表单验证规则
	const materialRules = {
		materialCode: [
			{ required: true, message: "请输入物料编码", trigger: "blur" },
		],
		materialName: [
			{ required: true, message: "请输入物料名称", trigger: "blur" },
		],
		specification: [
			{ required: true, message: "请输入规格型号", trigger: "blur" },
		],
		unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
		manufacturer: [
			{ required: true, message: "请输入制造商", trigger: "blur" },
		],
		applicationScene: [
			{ required: true, message: "请选择应用场景", trigger: "change" },
		],
		status: [{ required: true, message: "请选择状态", trigger: "change" }],
		categoryType: [
			{ required: true, message: "请选择分类", trigger: "change" },
		],
	};

	const categoryRules = {
		name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
	};

	// 获取字典标签
	const getDictLabel = (options, value) => {
		const item = options.find((item) => item.dictValue === value);
		return item ? item.dictLabel : value;
	};

	// 树节点过滤
	const filterNode = (value, data) => {
		if (!value) return true;
		return data.name.includes(value);
	};

	watch(treeFilterText, (val) => {
		treeRef.value.filter(val);
	});

	// 初始化分类统计图表
	const initCategoryChart = (data) => {
		nextTick(() => {
			if (!categoryChartRef.value) return;

			if (categoryChart) {
				categoryChart.dispose();
			}

			categoryChart = echarts.init(categoryChartRef.value);

			const option = {
				title: {
					text: "物料分类分布",
					left: "center",
				},
				tooltip: {
					trigger: "item",
				},
				legend: {
					orient: "vertical",
					left: "left",
				},
				series: [
					{
						name: "物料数量",
						type: "pie",
						radius: "70%",
						data: data?.pieData || [],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: "rgba(0, 0, 0, 0.5)",
							},
						},
					},
				],
			};

			categoryChart.setOption(option);

			const resizeHandler = () => {
				categoryChart.resize();
			};

			window.addEventListener("resize", resizeHandler);

			onUnmounted(() => {
				window.removeEventListener("resize", resizeHandler);
				if (categoryChart) {
					categoryChart.dispose();
					categoryChart = null;
				}
			});
		});
	};

	// 初始化状态占比图表
	const initStatusChart = (data) => {
		nextTick(() => {
			if (!statusChartRef.value) return;

			if (statusChart) {
				statusChart.dispose();
			}

			statusChart = echarts.init(statusChartRef.value);

			const option = {
				title: {
					text: "物料状态占比",
					left: "center",
				},
				tooltip: {
					trigger: "item",
					formatter: "{a} <br/>{b}: {c} ({d}%)",
				},
				legend: {
					orient: "vertical",
					left: "left",
				},
				series: [
					{
						name: "物料状态",
						type: "pie",
						radius: "70%",
						data: data || [],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: "rgba(0, 0, 0, 0.5)",
							},
						},
					},
				],
			};

			statusChart.setOption(option);

			const resizeHandler = () => {
				statusChart.resize();
			};

			window.addEventListener("resize", resizeHandler);

			onUnmounted(() => {
				window.removeEventListener("resize", resizeHandler);
				if (statusChart) {
					statusChart.dispose();
					statusChart = null;
				}
			});
		});
	};

	// 获取分类树数据
	const fetchCategoryTree = async () => {
		try {
			const { data } = await getMaterialCategoryList();
			categoryTreeData.value = data || [];
		} catch (error) {
			ElMessage.error("获取分类树失败");
		}
	};

	// 获取应用场景选项
	const fetchApplicationSceneList = async () => {
		try {
			const { data } = await getApplicationSceneList();
			applicationSceneOptions.value = data || [];
		} catch (error) {
			ElMessage.error("获取应用场景列表失败");
		}
	};

	// 获取物料列表
	const fetchMaterialList = async () => {
		try {
			loading.value = true;
			const params = {
				pageNum: pagination.currentPage,
				pageSize: pagination.pageSize,
				...searchForm,
				categoryType: searchForm.categoryType,
			};

			const data = await getMaterialCatalogList(params);
			tableData.value = data.rows || [];
			pagination.total = data.total || 0;
		} catch (error) {
			ElMessage.error("获取物料列表失败");
		} finally {
			loading.value = false;
		}
	};

	// 获取分类统计数据
	const fetchCategoryCountData = async () => {
		try {
			const { data } = await getCountByCategoryType();
			if (data) {
				initCategoryChart(data);
			} else {
				ElMessage.warning("分类统计数据格式不正确");
				initCategoryChart({ pieData: [] });
			}
		} catch (error) {
			console.error("获取分类统计数据失败:", error);
			ElMessage.error("获取分类统计数据失败");
			initCategoryChart({ pieData: [] });
		}
	};

	// 获取状态比例数据
	const fetchStatusRatioData = async () => {
		try {
			const { data } = await getRatioByStatus();
			if (data) {
				// 转换状态数据为图表所需格式
				const formattedData = data.map((item) => ({
					name: item.name,
					value: item.value,
					ratio: item.ratio,
				}));
				initStatusChart(formattedData);
			} else {
				ElMessage.warning("状态比例数据格式不正确");
				initStatusChart([]);
			}
		} catch (error) {
			console.error("获取状态比例数据失败:", error);
			ElMessage.error("获取状态比例数据失败");
			initStatusChart([]);
		}
	};

	// 树节点点击
	const handleNodeClick = (data) => {
		searchForm.categoryType = data.id;
		handleSearch();
	};

	// 搜索处理
	const handleSearch = () => {
		pagination.currentPage = 1;
		fetchMaterialList();
		// 搜索时更新图表数据
		fetchCategoryCountData();
		fetchStatusRatioData();
	};

	// 高级搜索
	const handleAdvancedSearch = () => {
		advancedSearchDialogVisible.value = true;
	};

	const handleAdvancedSearchSubmit = () => {
		Object.assign(searchForm, advancedSearchForm);
		advancedSearchDialogVisible.value = false;
		handleSearch();
	};

	const resetAdvancedSearch = () => {
		Object.keys(advancedSearchForm).forEach((key) => {
			advancedSearchForm[key] = key === "categoryType" ? [] : undefined;
		});
	};

	// 分页处理
	const handleSizeChange = (val) => {
		pagination.pageSize = val;
		fetchMaterialList();
	};

	const handleCurrentChange = (val) => {
		pagination.currentPage = val;
		fetchMaterialList();
	};

	// 选中行变化
	const handleSelectionChange = (selection) => {
		selectedRows.value = selection;
	};

	// 新增物料
	const handleAddMaterial = () => {
		materialDialogTitle.value = "新增物料";
		Object.keys(materialForm).forEach((key) => {
			materialForm[key] =
				key === "status" ? 0 : key === "categoryType" ? [] : "";
		});
		materialForm.id = null;
		materialDialogVisible.value = true;
	};

	// 编辑物料
	const handleEdit = async (row) => {
		try {
			loading.value = true;
			const { data } = await getMaterialCatalogDetail(row.id);
			if (data) {
				materialDialogTitle.value = "编辑物料";
				Object.assign(materialForm, data);
				materialForm.categoryType = data.categoryType
					? [data.categoryType]
					: [];
				materialDialogVisible.value = true;
			}
		} catch (error) {
			ElMessage.error("获取物料详情失败");
		} finally {
			loading.value = false;
		}
	};

	// 删除物料
	const handleDelete = (id) => {
		ElMessageBox.confirm("确认删除该物料吗?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				try {
					await deleteMaterialCatalog(id);
					ElMessage.success("删除成功");
					fetchMaterialList();
					// 更新图表
					fetchCategoryCountData();
					fetchStatusRatioData();
				} catch (error) {
					ElMessage.error("删除失败");
				}
			})
			.catch(() => {
				ElMessage.info("已取消删除");
			});
	};

	// 提交物料表单 - 修复files数组格式问题
	const submitMaterialForm = async () => {
		try {
			await materialFormRef.value.validate();

			// 关键修复：处理files字段为整数数组（后端要求）
			const fileIds = Array.isArray(materialForm.files)
				? materialForm.files.filter((id) => id !== "" && !isNaN(id)).map(Number) // 过滤无效值并转为数字
				: materialForm.files
				? materialForm.files
						.split(",")
						.filter((id) => id !== "" && !isNaN(id))
						.map(Number)
				: []; // 空值时直接传空数组

			// 处理分类ID
			const categoryId =
				materialForm.categoryType.length > 0
					? materialForm.categoryType[materialForm.categoryType.length - 1]
					: null;

			// 构建提交数据
			const formData = {
				...materialForm,
				files: fileIds, // 确保传递的是整数数组
				categoryType: categoryId,
			};

			// 新增时移除id属性
			if (!formData.id) {
				delete formData.id;
			}

			if (materialForm.id) {
				await updateMaterialCatalog(formData);
				ElMessage.success("更新成功");
			} else {
				await addMaterialCatalog(formData);
				ElMessage.success("新增成功");
			}

			materialDialogVisible.value = false;
			fetchMaterialList();
			fetchCategoryCountData();
			fetchStatusRatioData();
		} catch (error) {
			if (error.name !== "ValidationError") {
				ElMessage.error(error.response?.data?.msg || "操作失败，请重试");
			}
		}
	};

	// 新增分类
	const handleAddCategory = () => {
		categoryDialogTitle.value = "新增分类";
		categoryForm.name = "";
		categoryForm.parentId = null;
		categoryForm.id = null;
		categoryDialogVisible.value = true;
	};

	// 编辑分类
	const handleEditCategory = (node) => {
		categoryDialogTitle.value = "编辑分类";
		categoryForm.id = node.id;
		categoryForm.name = node.name;
		categoryForm.parentId = node.parentId;
		categoryDialogVisible.value = true;
	};

	// 提交分类表单
	const submitCategoryForm = async () => {
		try {
			await categoryFormRef.value.validate();

			const formData = {
				...categoryForm,
				parentId: Array.isArray(categoryForm.parentId)
					? categoryForm.parentId.length > 0
						? categoryForm.parentId[categoryForm.parentId.length - 1]
						: 0
					: categoryForm.parentId,
			};

			if (categoryForm.id) {
				// 编辑
				await updateMaterialCategory(formData);
				ElMessage.success("更新分类成功");
			} else {
				// 新增
				await addMaterialCategory(formData);
				ElMessage.success("新增分类成功");
			}

			categoryDialogVisible.value = false;
			fetchCategoryTree();
			// 更新图表
			fetchCategoryCountData();
		} catch (error) {
			if (error.response) {
				ElMessage.error(error.response.data.msg || "操作失败");
			}
		}
	};

	// 删除分类
	const handleDeleteCategory = (id) => {
		ElMessageBox.confirm("确认删除该分类吗?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				try {
					await deleteMaterialCategory(id);
					ElMessage.success("删除分类成功");
					fetchCategoryTree();
					// 更新图表
					fetchCategoryCountData();
				} catch (error) {
					ElMessage.error("删除分类失败");
				}
			})
			.catch(() => {
				ElMessage.info("已取消删除");
			});
	};

	// 批量导入
	const handleImport = () => {
		ElMessage.info("批量导入功能");
	};

	// 导出
	const handleExport = async () => {
		try {
			const params = {
				...searchForm,
			};

			await exportMaterialCatalog(params);
			ElMessage.success("导出成功");
		} catch (error) {
			ElMessage.error("导出失败");
		}
	};

	onMounted(() => {
		fetchCategoryTree();
		fetchApplicationSceneList();
		// 等待DOM渲染完成后初始化图表
		nextTick(() => {
			fetchCategoryCountData();
			fetchStatusRatioData();
		});
	});

	// 组件卸载时清理
	const onUnmounted = (callback) => {
		// 实际项目中使用Vue的onUnmounted
	};
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.tree-card {
		height: calc(75vh);
		display: flex;
		flex-direction: column;
	}

	.search-box {
		margin-bottom: 15px;
	}

	.tree-node {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}

	.tree-count {
		color: #999;
		font-size: 12px;
	}

	.tree-footer {
		margin-top: auto;
		padding-top: 15px;
		border-top: 1px solid #eee;
	}

	.content-card {
		height: calc(75vh);
		display: flex;
		flex-direction: column;
	}

	/* 图表样式 */
	.chart-row {
		margin-bottom: 20px;
		height: 300px;
	}

	.chart-container {
		width: 100%;
		height: 100%;
	}

	.chart {
		width: 100% !important;
		height: 100% !important;
	}

	.search-bar {
		margin-bottom: 15px;
		display: flex;
		gap: 10px;
	}

	.operation-buttons {
		margin-bottom: 15px;
		display: flex;
		gap: 10px;
		align-items: center;
	}

	.selection-info {
		margin-left: auto;
		color: #666;
		font-size: 14px;
	}

	.pagination {
		margin-top: 15px;
	}
</style>
